// src/services/invites.js - 邀请码相关服务

import { post, get } from './api';
import {
  generateInviteCode as localGenerateInviteCode,
  saveInviteCode as localSaveInviteCode,
  getUserInviteCodes as localGetUserInviteCodes,
  deleteInviteCode as localDeleteInviteCode
} from '../utils/localStorage';

/**
 * 生成邀请码
 * @returns {Promise} - 生成结果
 */
export const generateInviteCode = async () => {
  try {
    // 先生成本地邀请码对象以备用
    const generateResult = localGenerateInviteCode();
    if (!generateResult.success) {
      return {
        success: false,
        message: generateResult.message || '生成邀请码失败'
      };
    }

    const inviteCode = generateResult.inviteCode;
    const code = inviteCode.code;

    try {
      // 调用后端API生成邀请码
      const response = await post('/invites/generate', { code });

      if (response && response.code === 200) {
        return {
          success: true,
          message: response.message || '邀请码生成成功',
          data: {
            inviteCode: inviteCode
          }
        };
      } else {
        // 后端API失败，回退到本地存储
        console.warn('邀请码生成API失败，使用本地存储:', response);

        const saveResult = localSaveInviteCode(generateResult.inviteCode);
        if (!saveResult.success) {
          return {
            success: false,
            message: saveResult.message || '存储邀请码失败'
          };
        }

        return {
          success: true,
          message: '邀请码生成成功（本地模式）',
          data: {
            inviteCode: generateResult.inviteCode
          }
        };
      }
    } catch (apiError) {
      // API调用出错，回退到本地存储
      console.warn('邀请码生成API连接失败，使用本地存储:', apiError);

      const saveResult = localSaveInviteCode(generateResult.inviteCode);
      if (!saveResult.success) {
        return {
          success: false,
          message: saveResult.message || '存储邀请码失败'
        };
      }

      return {
        success: true,
        message: '邀请码生成成功（本地模式）',
        data: {
          inviteCode: generateResult.inviteCode
        }
      };
    }
  } catch (error) {
    console.error('生成邀请码过程出错:', error);
    return {
      success: false,
      message: error.message || '生成邀请码失败'
    };
  }
};

/**
 * 获取用户邀请码列表
 * @returns {Promise} - 用户邀请码列表
 */
export const getUserInviteCodes = async () => {
  try {
    // 调用后端API获取用户自己的邀请码
    const response = await get('/invites/own');

    if (response && response.code === 200) {
      return {
        success: true,
        data: response.data
      };
    } else {
      // 后端API失败，回退到本地存储
      console.warn('获取邀请码API失败，使用本地存储:', response);

      const inviteCodes = localGetUserInviteCodes();
      return {
        success: true,
        data: {
          inviteCodes
        }
      };
    }
  } catch (error) {
    console.warn('获取邀请码API连接失败，使用本地存储:', error);

    // 使用localStorage获取用户邀请码
    const inviteCodes = localGetUserInviteCodes();

    return {
      success: true,
      data: {
        inviteCodes
      }
    };
  }
};

/**
 * 删除邀请码
 * @param {string} code - 邀请码
 * @returns {Promise} - 删除结果
 */
export const deleteInviteCode = async (code) => {
  try {
    // 调用后端API删除邀请码
    const response = await post(`/invites/delete/${code}`);

    if (response && response.code === 200) {
      return {
        success: true,
        message: response.message || '邀请码删除成功'
      };
    } else {
      // 后端API失败，回退到本地存储
      console.warn('删除邀请码API失败，使用本地存储:', response);

      const result = localDeleteInviteCode(code);
      return {
        success: result.success,
        message: result.message || (result.success ? '邀请码删除成功' : '邀请码删除失败')
      };
    }
  } catch (error) {
    console.warn('删除邀请码API连接失败，使用本地存储:', error);

    // 使用localStorage删除邀请码
    const result = localDeleteInviteCode(code);

    return {
      success: result.success,
      message: result.message || (result.success ? '邀请码删除成功' : '删除邀请码失败')
    };
  }
}; 